<template>
  <div class="map-container">
    <div id="map" class="map"></div>
  </div>
</template>

<script>
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'

export default {
  name: 'MaskDemo',
  data() {
    return {
      map: null,
      maskLayer: null,
      baseLayer: null,
      boundaryLayer: null,
      worldBounds: [
        [-90, -180],
        [90, 180]
      ]
    }
  },
  mounted() {
    this.initMap()
    this.loadBoundaryData()
  },
  methods: {
    initMap() {
      // 初始化地图
      this.map = L.map('map', {
        center: [43.792818, 87.617733], // 乌鲁木齐市中心坐标
        zoom: 6,
        zoomControl: true
      })

      // 添加高德底图
      this.baseLayer = L.tileLayer('https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', {
        subdomains: ["1", "2", "3", "4"],
        attribution: '&copy; 高德地图'
      }).addTo(this.map)
    },

    async loadBoundaryData() {
      try {
        const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/650000.json')
        const geoData = await response.json()

        // 创建边界图层
        this.boundaryLayer = L.geoJSON(geoData, {
          style: {
            color: '#f56c6c',
            weight: 2,
            opacity: 1,
            fillOpacity: 0
          }
        }).addTo(this.map)

        // 创建遮罩图层
        this.createMaskLayer(geoData)

        // 调整视图范围
        this.map.fitBounds(this.boundaryLayer.getBounds(), {
          padding: [50, 50]
        })
      } catch (error) {
        console.error('加载边界数据失败:', error)
      }
    },

    createMaskLayer(geoData) {
      // 创建一个包含世界范围和新疆区域的多边形
      const maskGeoJson = {
        type: 'Feature',
        geometry: {
          type: 'Polygon',
          coordinates: [
            // 外部矩形（世界范围）
            [
              [-180, 90],
              [180, 90],
              [180, -90],
              [-180, -90],
              [-180, 90]
            ]
          ]
        }
      }

      // 将新疆边界作为内部孔洞
      maskGeoJson.geometry.coordinates.push(...geoData.features[0].geometry.coordinates[0])

      // 创建遮罩图层
      this.maskLayer = L.geoJSON(maskGeoJson, {
        style: {
          color: '#ffffff',
          weight: 0,
          fillColor: '#1976d2',
          fillOpacity: 0.3,
          interactive: false
        }
      }).addTo(this.map)
    }
  },
  beforeDestroy() {
    if (this.map) {
      this.map.remove()
    }
  }
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100vh;
  position: relative;
}

.map {
  width: 100%;
  height: 100%;
}
</style> 